<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="部门">
        <el-select
          clearable
          v-model="dataForm.departmentName"
          placeholder="请选择所属部门"
        >
          <el-option :value="departmentDataTree" style="height: auto">
            <el-tree
              :data="departmentDataTree"
              accordion
              node-key="id"
              ref="deptListTree"
              highlight-current
              :props="deptListTreeProps"
              @check-change="deptListTreeCurrentChangeHandle"
              check-on-click-node
            >
            </el-tree>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="dataForm.username" placeholder="登录帐号"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="dataForm.gender">
          <el-radio :label="0">女</el-radio>
          <el-radio :label="1">男</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="密码" prop="password" :class="{ 'is-required': !dataForm.id }" v-show="!dataForm.id">
        <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword" :class="{ 'is-required': !dataForm.id }" v-show="!dataForm.id">
        <el-input v-model="dataForm.confirmPassword" type="password" placeholder="确认密码"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="角色" size="mini" prop="roleIdList">
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{
              role.roleName
            }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      <el-button @click="visible = false">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {isEmail, isMobile} from '@/utils/validate'

export default {
  data () {
    let validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    let validateConformPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('确认密码不能为空'))
      } else if (this.dataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else {
        callback()
      }
    }
    let validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    let validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      // 部门
      departmentDataTree: [],
      dataFormFromAdmin: {},
      dataForm: {
        id: 0,
        username: '',
        gender: '',
        password: '',
        confirmPassword: '',
        salt: '',
        email: '',
        mobile: '',
        status: 1,
        departmentId: '',
        departmentName: '',
        roleIdList: []
      },
      deptListTreeProps: {
        label: 'name',
        children: 'children'
      },
      // 角色列表
      roleList: [],
      dataRule: {
        username: [
          {required: true, message: '用户名不能为空', trigger: 'blur'}
        ],
        password: [
          {validator: validatePassword, trigger: 'blur'}
        ],
        confirmPassword: [
          {validator: validateConformPassword, trigger: 'blur'}
        ],
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'},
          {validator: validateEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '手机号不能为空', trigger: 'blur'},
          {validator: validateMobile, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    init (id) {
      // 有id为修改，没有id则为添加
      this.dataForm.id = id || 0
      this.$http({
        url: this.$http.adornUrl('/sys/role/select'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        this.roleList = data && data.code === 200 ? data.list : []
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        // 更新
        if (this.dataForm.id) {
          this.dataForm.username = this.dataFormFromAdmin.username
          this.dataForm.gender = this.dataFormFromAdmin.gender
          this.dataForm.salt = this.dataFormFromAdmin.salt
          this.dataForm.email = this.dataFormFromAdmin.email
          this.dataForm.mobile = this.dataFormFromAdmin.mobile
          this.dataForm.status = this.dataFormFromAdmin.status
          this.dataForm.departmentId = this.dataFormFromAdmin.departmentId
          this.dataForm.departmentName = this.dataFormFromAdmin.department
          this.dataForm.roleIdList = this.dataFormFromAdmin.roleIdList
        } else {
          this.dataForm.departmentId = ''
          this.dataForm.departmentName = ''
        }
      })

    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sys/admin/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'userId': this.dataForm.id || undefined,
              'username': this.dataForm.username,
              'gender': this.dataForm.gender,
              'password': this.dataForm.password,
              'salt': this.dataForm.salt,
              'email': this.dataForm.email,
              'mobile': this.dataForm.mobile,
              'status': this.dataForm.status,
              'departmentId': this.dataForm.departmentId,
              'roleIdList': this.dataForm.roleIdList,
              'createUserId': this.$store.state.user.id
            })
          }).then(({data}) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    // 部门树选中节点
    deptListTreeCurrentChangeHandle (data, node) {
      this.dataForm.departmentId = data.id
      this.dataForm.departmentName = data.name
    },
  }
}
</script>

<style scoped>

</style>
